import { defineStore } from 'pinia'
import { LoginParams, UserStore } from '@/api/user/type'
import { reqLogin } from '@/api/user'
import { SET_TOKEN, GET_TOKEN } from '@/utils/user'

const useUserStore = defineStore('user', {
  state: (): UserStore => ({
    // 控制登录组件的显示与隐藏
    visiable: false,
    userInfo: GET_TOKEN()
      ? JSON.parse(GET_TOKEN() as string)
      : {
          name: '',
          token: ''
        }
  }),

  actions: {
    // 登录请求
    async userLogin(loginParams: LoginParams) {
      const { data } = await reqLogin(loginParams)
      this.userInfo = data
      SET_TOKEN(JSON.stringify(data))
      this.visiable = false
      return 'ok'
    },
    // 退出登录
    logout() {
      this.userInfo = {
        name: '',
        token: ''
      }
      SET_TOKEN('')
    }
  }
})

export default useUserStore
